package quq.missq.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;

import java.util.ArrayList;

import cn.sharesdk.framework.ShareSDK;
import quq.missq.BaseFragmentActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.adapter.ListFragmentAdapter;
import quq.missq.beans.UserBean;
import quq.missq.fragments.GoddessFragment;
import quq.missq.fragments.LoveBigShootFragment;
import quq.missq.fragments.MySubscribeFragment;
import quq.missq.utils.SharePreUtils;
import quq.missq.utils.UIHelper;
import quq.missq.utils.UserTools;


public class MainActivity extends BaseFragmentActivity implements View.OnClickListener{

    private ViewPager mViewPager;
    private ListFragmentAdapter adapter;
    private ArrayList<Fragment> fragments;
    private TextView mBigShoot;
    private TextView mAnswer;
    private TextView mDreamGirl;
    private ImageView mTabLine;
    private int mScreen1_3;
    private int mCurrentPageIndex;
    private RelativeLayout mMember;
   // private RelativeLayout mPublish;
    private RelativeLayout mSubscrible;
    private TextView jiaobiaoNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
        initListener();

        if(UserTools.getUser(this) != null){
            MLog.e("token",UserTools.getUser(this).getAcc_token());
        }
        ShareSDK.initSDK(this);
        // 注册一个cmd消息的BroadcastReceiver  这段代码不要删 环信需要
        IntentFilter cmdIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction());
        registerReceiver(cmdMessageReceiver, cmdIntentFilter);
        EMChat.getInstance().setAppInited();
    }

    /**
     * cmd消息BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            //获取cmd message对象
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            //获取消息body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String aciton = cmdMsgBody.action;//获取自定义action
            //获取扩展属性
//            String attr = "";
//            try {
//                attr = message.getStringAttribute("ext");
//            } catch (EaseMobEßxception e) {
//                e.printStackTrace();
//            }
//            Log.e("xxxxxxxxxxx",attr);
        }
    };

    private void initView(){
        mViewPager = (ViewPager)findViewById(R.id.viewPager);
        mBigShoot = (TextView)findViewById(R.id.bigShoot);
        //mViewPager.setOffscreenPageLimit(0);
        mAnswer = (TextView)findViewById(R.id.answer);
        mDreamGirl = (TextView)findViewById(R.id.dreamGirl);
        mTabLine = (ImageView)findViewById(R.id.tabLine);
        mMember = (RelativeLayout)findViewById(R.id.member);
       // mPublish = (RelativeLayout)findViewById(R.id.publish);
        mSubscrible = (RelativeLayout)findViewById(R.id.chatList);
        jiaobiaoNumber = (TextView)findViewById(R.id.jiaobiaoNumber);
        initTabLine();
    }

    @Override
    protected void onResume() {
        super.onResume();
        int totalCount = SharePreUtils.getInt(this, Constants.TOTALCOUNT,0);
        if(totalCount > 0){
            jiaobiaoNumber.setVisibility(View.VISIBLE);
            if(totalCount > 99){
                jiaobiaoNumber.setText(totalCount+"+");
            }else{
                jiaobiaoNumber.setText(totalCount+"");
            }

        }else{
            jiaobiaoNumber.setVisibility(View.GONE);
        }
    }

    private void initData(){
        adapter = new ListFragmentAdapter(getSupportFragmentManager());
        fragments = new ArrayList<>();
        fragments.add(new LoveBigShootFragment());
        fragments.add(new GoddessFragment());
        //fragments.add(new TalkLoveFragment());
        fragments.add(new MySubscribeFragment());
        adapter.setData(fragments);
        mViewPager.setOffscreenPageLimit(0);
        mViewPager.setAdapter(adapter);
    }

    private void initListener(){
        mMember.setOnClickListener(this);
        //mPublish.setOnClickListener(this);
        mSubscrible.setOnClickListener(this);
        mBigShoot.setOnClickListener(this);
        mAnswer.setOnClickListener(this);
        mDreamGirl.setOnClickListener(this);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPx) {

                LinearLayout.LayoutParams lp =
                        (LinearLayout.LayoutParams) mTabLine.getLayoutParams();
                //0->1
                if (mCurrentPageIndex == 0 && position == 0) {
                    lp.leftMargin = (int) (positionOffset * mScreen1_3 + mCurrentPageIndex* mScreen1_3);
                }
                //1->0
                else if (mCurrentPageIndex == 1 && position == 0) {
                    lp.leftMargin = (int) (mCurrentPageIndex * mScreen1_3 + (positionOffset - 1)* mScreen1_3);
                }
                //1->2
                else if (mCurrentPageIndex == 1 && position == 1) {
                    lp.leftMargin = (int) (mCurrentPageIndex * mScreen1_3 + positionOffset* mScreen1_3);
                }
                // 2->1
                else if (mCurrentPageIndex == 2 && position == 1) {
                    lp.leftMargin = (int) (mCurrentPageIndex * mScreen1_3 + (positionOffset - 1)
                            * mScreen1_3);
                }
                mTabLine.setLayoutParams(lp);
            }

            @Override
            public void onPageSelected(int i) {
                mCurrentPageIndex = i;
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });
    }

    private void initTabLine() {
        mTabLine = (ImageView) findViewById(R.id.tabLine);
        mScreen1_3 = UIHelper.getScreenWidth(this)/3;
        ViewGroup.LayoutParams lp = mTabLine.getLayoutParams();
        lp.width = mScreen1_3;
        mTabLine.setLayoutParams(lp);
    }

    private static final int PUBLISH_TOPIC= 0;
    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.bigShoot:
                mViewPager.setCurrentItem(0);
                break;
            case R.id.dreamGirl:
                mViewPager.setCurrentItem(1);
                break;
            case R.id.answer:
                mViewPager.setCurrentItem(2);
                break;
            case R.id.member:
                goOtherActvity(MyInformationActivity.class);
                break;
//            case R.id.publish:
//                if(UserTools.getUser(this) == null){
//                    intent = new Intent();
//                    intent.setClass(this,LoginActivity.class);
//                    startActivity(intent);
//                }else{
//                    intent = new Intent();
//                    intent.setClass(this, PublishTopicActivity.class);
//                    startActivityForResult(intent, PUBLISH_TOPIC);
//                }
//                break;
            case R.id.chatList:
                intent = new Intent();
                intent.setClass(this, AuthorSearchActivity.class);
                startActivity(intent);
                break;
            default:break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode == RESULT_OK && requestCode == PUBLISH_TOPIC){
            mViewPager.setCurrentItem(1);
            Fragment fragment = adapter.getItem(mViewPager.getCurrentItem());
            fragment.onResume();
        }
    }

    private void goOtherActvity(Class z){
        UserBean.User user = UserTools.getUser(this);
        Intent intent = new Intent();
        if(user == null){
            intent.setClass(this,LoginActivity.class);
        }else{
            int userAuth = user.getAuth();//跳转到个人信息页面的时候需要根据用户类型来判断是否屏蔽我的相册功能。
            intent.putExtra("userAuth",userAuth);
            intent.setClass(this,z);
        }
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);//true对任何Activity都适用
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(this);//如果不stop掉，应用启动次数将不准确
        unregisterReceiver(cmdMessageReceiver);
    }
}
